﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using agile_tool.userControl;

namespace agile_tool
{
    /// <summary>
    /// Interaction logic for userStoryForSprintPage.xaml
    /// </summary>
    public partial class userStoryForSprintPage : UserControl, IGenericPagesData
    {
        Button createNewuserStory;
        create createuserStorySprintItem;
        int sprintId;
        int projectId;
        public string navigationName = "";
        List<timeAssignmentPage> ltap = new List<timeAssignmentPage>();
        public userStoryForSprintPage(int sprintId, string filter, string sprintName)
        {
            InitializeComponent();
            this.sprintId = sprintId;
            navigationName = sprintName + "'s User Stories";
            refresh(filter);
        }
        
        public string getNavigationName()
        {
            return navigationName;
        }
        public int getId()
        {
            return sprintId;
        }
        public void refresh(string filter)
        {
            lbUserStorys.Items.Clear();
            int sprintDuration=0;
            DateTime tmp = new DateTime(1333,10,10);
            DateTime sprintStartDate = tmp;
            DataClasses1DataContext db = new DataClasses1DataContext();
            var Sprints = from p in db.tblSprints where p.id == sprintId select p;
            projectId = (int)Sprints.First().projectId;
            try
            {
                sprintStartDate = (DateTime)Sprints.First().startDate;
                sprintDuration = (int)Sprints.First().tblProject.sprintDuration;
            }
            catch { }

            if (sprintStartDate != tmp && sprintDuration != 0)
            {
            try
            {
                var userStorysSprints = from p in db.tblUserStorySprints where p.sprintId == sprintId select p;
                
                    projectId = userStorysSprints.First().tblUserStory.tblProject.pId;
                    foreach (var p in userStorysSprints)
                    {
                        if (filter == "")
                        {
                            userStorySprintItem theuserStorySprintItem = new userStorySprintItem();
                            theuserStorySprintItem.tbName.Text = p.tblUserStory.name;
                            theuserStorySprintItem.tbDesc.Text = p.tblUserStory.description;
                            theuserStorySprintItem.tbPriority.Text = p.tblUserStory.Priority.ToString();
                            theuserStorySprintItem.tbEffort.Text = p.tblUserStory.effort.ToString();
                            theuserStorySprintItem.id = p.id;

                            var tasks = from g in db.tblTasks where g.userStoryId == p.userStoryId select g;
                            foreach (var task in tasks)
                            {
                                timeAssignmentPage tap = new timeAssignmentPage();
                                tap.tbName.Text = task.name;
                                tap.taskId = task.id;
                                timeAssignmentItem tbi = new timeAssignmentItem();
                                tbi.spHeader.Visibility = Visibility.Visible;
                                tbi.spBody.Visibility = Visibility.Collapsed;
                                tap.cbTaskTimes.Items.Add(tbi);
                                try
                                {
                                    task.tblTaskHours.First();
                                    foreach (var t in task.tblTaskHours)
                                    {
                                        tbi = new timeAssignmentItem();
                                        tbi.taskHourId = (int)t.id;
                                        tbi.taskId = task.id;
                                        tbi.dpDate.SelectedDate = t.date;
                                        tbi.tbRemainng.Text = (t.remaining).ToString();
                                        tbi.btnSave.Click += new RoutedEventHandler(btnTBISave_Click2);
                                        tbi.tbRemainng.TextChanged += new TextChangedEventHandler(tbRemainng_TextChanged);
                                        tap.cbTaskTimes.Items.Add(tbi);
                                    }
                                }
                                catch
                                {
                                    if (task.expectedHours != null)
                                    {
                                        for (int i = 0; i <= sprintDuration; i++)
                                        {
                                            tbi = new timeAssignmentItem();
                                            tbi.dpDate.SelectedDate = sprintStartDate.AddDays(i);
                                            tbi.tbRemainng.Text = (task.expectedHours).ToString();
                                            tbi.btnSave.Click += new RoutedEventHandler(btnTBISave_Click2);
                                            tap.cbTaskTimes.Items.Add(tbi);
                                            tblTaskHour tth = new tblTaskHour { remaining = task.expectedHours, date = (DateTime)tbi.dpDate.SelectedDate, taskId = task.id };
                                            db.tblTaskHours.InsertOnSubmit(tth);
                                            db.SubmitChanges();
                                            tbi.taskHourId = tth.id;
                                            tbi.taskId = task.id;
                                        }
                                    }
                                    else
                                    {
                                        tbi = new timeAssignmentItem();
                                        tbi.spHeader.Visibility = Visibility.Visible;
                                        tbi.spBody.Visibility = Visibility.Hidden;
                                        tbi.tbFirstTitle.Text = "Please fill Expected Hour";
                                        tap.cbTaskTimes.Items.Add(tbi);
                                    }
                                }
                                theuserStorySprintItem.lbTasks.Items.Add(tap);
                                ltap.Add(tap);
                            }
                           
                            theuserStorySprintItem.btnDell.Click += new RoutedEventHandler(btnDell_Click);
                            lbUserStorys.Items.Add(theuserStorySprintItem);
                        }
                    }
            }
            catch { }
            createNewuserStory = new Button { Content = "Add New User Story To This Sprint" };
            createNewuserStory.Click += new RoutedEventHandler(createNewuserStory_Click);
            createNewuserStory.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            lbUserStorys.Items.Add(createNewuserStory);
                }
            else
            {
                MessageBox.Show("Please Set The Starting Date And Sprint Duration Before This Step");
                lbUserStorys.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        void tbRemainng_TextChanged(object sender, TextChangedEventArgs e)
        {
            foreach(timeAssignmentPage p in  ltap)
            {
            p.fixTheTimes();
            }

        }

        void btnTBISave_Click2(object sender, RoutedEventArgs e)
        {
            timeAssignmentItem _timeAssignmentPage = new timeAssignmentItem();
            _timeAssignmentPage = (timeAssignmentItem)helper.FindParrentUserControl(((DependencyObject)sender), _timeAssignmentPage.GetType().ToString());
           
                DataClasses1DataContext db = new DataClasses1DataContext();
                tblTaskHour tth = (from p in db.tblTaskHours where p.id == _timeAssignmentPage.taskHourId select p).First();
                tth.remaining = int.Parse(_timeAssignmentPage.tbRemainng.Text);
                db.SubmitChanges();
        }

        public static void deleteUserStory(int id) 
        {
            DataClasses1DataContext db = new DataClasses1DataContext();

            var tbac = from p in db.tblAcceptanceCriterias where p.userStoryId == id select p;
            db.tblAcceptanceCriterias.DeleteAllOnSubmit(tbac);
            db.SubmitChanges();

            var tbtas = from p in db.tblTasks where p.userStoryId == id select p;
            db.tblTasks.DeleteAllOnSubmit(tbtas);
            db.SubmitChanges();

            var tbUserSp = from p in db.tblUserStorySprints where p.userStoryId == id select p;
            db.tblUserStorySprints.DeleteAllOnSubmit(tbUserSp);
            db.SubmitChanges();

            tblUserStory tb = (from p in db.tblUserStories where p.id == id select p).First();
            db.tblUserStories.DeleteOnSubmit(tb);
            db.SubmitChanges();
        }

        void btnDell_Click(object sender, RoutedEventArgs e)
        {
            userStorySprintItem theuserStorySprintItem = new userStorySprintItem();
            theuserStorySprintItem = (userStorySprintItem)helper.FindParrentUserControl(((Button)sender), theuserStorySprintItem.GetType().ToString());

            deleteUserStory(theuserStorySprintItem.id);

            lbUserStorys.Items.Remove(theuserStorySprintItem);
        }

        void createNewuserStory_Click(object sender, RoutedEventArgs e)
        {
            lbUserStorys.Items.Remove(createNewuserStory);
            createuserStorySprintItem = new create();
            createuserStorySprintItem.tbName.Visibility = Visibility.Collapsed;
            createuserStorySprintItem.lbList.Visibility = Visibility.Visible;
            createuserStorySprintItem.btnSave.Content = "Add";
            createuserStorySprintItem.btnCancel.Click += new RoutedEventHandler(btnCancel_Click);
            createuserStorySprintItem.btnSave.Click += new RoutedEventHandler(btnSave_Click);
            DataClasses1DataContext db = new DataClasses1DataContext();
             var userStories = from p in db.tblUserStories where p.projectId == projectId select p;
             foreach (var p in userStories)
             {
                 ListBoxItem lbi = new ListBoxItem();
                 lbi.Tag = p.id;
                 lbi.Content = p.name;
                 createuserStorySprintItem.lbList.Items.Add(lbi);
             }


            lbUserStorys.Items.Add(createuserStorySprintItem);
        }

        void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (createuserStorySprintItem.lbList.SelectedIndex != -1)
            {
                DataClasses1DataContext db = new DataClasses1DataContext();
                var a = from p in db.tblUserStorySprints
                        where
                            p.sprintId == sprintId &&
                            p.userStoryId == int.Parse(((ListBoxItem)createuserStorySprintItem.lbList.SelectedItem).Tag.ToString())
                        select p;

                try { 
                    a.First();
                    MessageBox.Show("This user story has been added before");
                }
                catch
                {
                    tblUserStorySprint tp = new tblUserStorySprint
                    {
                        sprintId = sprintId,
                        userStoryId = int.Parse(((ListBoxItem)createuserStorySprintItem.lbList.SelectedItem).Tag.ToString())
                    };

                    db.tblUserStorySprints.InsertOnSubmit(tp);
                    db.SubmitChanges();
                }
                refresh("");
            }
            else
            {
                MessageBox.Show("You Should Select a User Story ");
            }
        }

        void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            refresh("");
        }
    }
}
